package giermala.dominik.fotka.controller;

import giermala.dominik.fotka.domain.Foto;
import giermala.dominik.fotka.domain.User;
import giermala.dominik.fotka.repository.FotoRepository;
import giermala.dominik.fotka.repository.UserRepository;

import java.security.Principal;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping(value = "/upload")
public class UploadController {
	
	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
	
	@Autowired
    private FotoRepository fotoRepository;
	@Autowired
	private UserRepository userRepository;
	
	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute(new UploadItem());
		return "upload";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(UploadItem uploadItem, BindingResult result, Principal principal) {

		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				logger.info("Error: " + error.getCode() + " - " + error.getDefaultMessage());
			}
			return "upload";
		}
		createAndSaveFoto(uploadItem, principal);

		return "redirect:/logged.html";
	}

	private void createAndSaveFoto(UploadItem uploadItem, Principal principal) {
		Foto foto = new Foto();
		User user = getUser(principal);
		user.getFotos().add(foto);
		foto.setFotkaUser(user);
		foto.setImage(getImage(uploadItem));
		foto.setName(getName(uploadItem));
		foto.setDate(new Date());
		foto.setAverageNote(0);
		foto.setNotesCounter(0);
		fotoRepository.saveAndFlush(foto);
	}

	private String getName(UploadItem uploadItem) {
		return uploadItem.getFileData().getOriginalFilename();
	}

	private byte[] getImage(UploadItem uploadItem) {
		return uploadItem.getFileData().getBytes();
	}
	
	private User getUser(Principal principal) {
		String username = principal.getName();
		User user = userRepository.findByUsername(username);
		return user;
	}
	
	
	public static class UploadItem {
	    private String filename;
	    private CommonsMultipartFile fileData;

	    public String getFilename() {
	            return filename;
	    }

	    public void setFilename(String filename) {
	            this.filename = filename;
	    }

	    public CommonsMultipartFile getFileData() {
	            return fileData;
	    }

	    public void setFileData(CommonsMultipartFile fileData) {
	            this.fileData = fileData;
	    }
	}
}